import React from 'react';
import {Table, Row, Col, Form, Input, InputNumber, Select, Button, Modal, Tabs} from 'antd';

import CurrencySelect from '../../../components/commons/CurrencySelect';
import SingleDragger from "../../../components/commons/SingleDragger";
import OperatorConstant from "../../../utils/OperatorConstant";
import BizParams from "../../../components/commons/BizParams";
import {download} from '../../../utils/commons'
import Constants from "../../../utils/Constants";
const R = require('ramda');
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;


export default Form.create({wrappedComponentRef: true})(class EditProduct extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            open: false,
            disabled: true,
            type: "",
            require_memo:true,
            require_other:true,
            loading: false


        }
    }

    handleDownloadTable =() => {
        download(apiPath.zbtie+"/api/table/download", {filename:"申报要素对照表.xlsx"});
    }

    handleResetFields = () => {
        this.refs.productFacade.resetUpload();
        this.refs.productOther.resetUpload();
        this.refs.productCartons.resetUpload();
        this.refs.productBranchModel.resetUpload();
        this.props.form.resetFields();

    }

    handleCancel = () => {
        this.handleResetFields();
        this.setState({open:false,require_other:true,require_memo:true,loading:false})
        this.props.dispatch({
            type: 'customerManage/setProduct',
            payload: {
                recAcc: "",
            }
        });
        this.props.dispatch({
            type: "productApproval/setHscode",
            payload: {
                hscode : {}
            }
        });
    }

    handleOpen = (type, disable) => {
        this.state.type = type;

        if(!R.isNil(disable)){
            this.state.disabled = disable;
        }
        this.setState({open: true});

    }

    handleConfirm = (method) => {


        this.props.form.validateFields({ force: true }, (errors, values) => {
            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource
            if (errors){
                return;
            }

            if(this.state.type == OperatorConstant.view){
                return;
            }

            if(this.state.type == OperatorConstant.approval){
                if(this.state.disabled == true){
                    return;
                }
                this.setState({ loading: true });

                this.props.dispatch({
                    type: "productApproval/productApproval",
                    payload: {
                        id : dataSource.id,
                        hscode : values.hscode,
                        priceisok: values.priceisok ,
                        iseffecthscode: values.iseffecthscode ,
                        drawbackcode: values.drawbackcode ,
                        approvalresult: values.approvalresult ,
                        approvalmemo: values.approvalmemo ,
                        onSuccess:()=>{
                            this.props.handleSearch();
                            this.handleCancel();
                        },
                        onFail: () => this.setState({loading: false})
                    }
                })
            }else{
                let type = "";
                if (this.state.type == OperatorConstant.add) {
                    type = "customerManage/addProduct";


                } else if (this.state.type == OperatorConstant.edit) {
                    type = "customerManage/updateProduct";

                }

                let productFacade = this.refs.productFacade.getUrl();
                let productBranchModel = this.refs.productBranchModel.getUrl();
                let productCartons = this.refs.productCartons.getUrl();
                let productOtherFile = this.refs.productOther.getUrl();

                this.props.dispatch({
                    type: type,
                    payload: {
                        method: method,
                        cstid: this.props.cstId,
                        id: dataSource.id,
                        name: values.name,
                        nameEn: values.nameEn,
                        branch: values.branch,
                        model: values.model,
                        currency: values.currency,
                        price: values.price,
                        unit: values.unit,
                        weight: values.weight,
                        size: values.size,
                        declarelements: values.declarelements,
                        exporttype: values.exporttype,
                        sourcetype: values.sourcetype,
                        memo: values.memo,
                        hscodehis: values.hscodehis,
                        branchtype: values.branchtype,
                        costPrice: values.costPrice,
                        productFacade: productFacade,
                        productBranchModel: productBranchModel,
                        productCartons: productCartons,
                        productOtherFile: productOtherFile,
                        status: this.props.businessType != "2" ? "1" : "4",
                        onSuccess: () => {
                            if(this.props.isCstPoduct){
                                this.props.handleSearch();

                            }else{
                                this.props.dispatch({
                                    type: 'orderProduct/queryProductList',
                                    payload: {
                                        productName: '',
                                        cstId: this.props.cstId,
                                        page: Constants.DEFAULTPAGE
                                    }
                                });
                            }
                            this.handleCancel();
                        },
                        onFail: () => this.setState({loading: false})
                    }
                })

            }


        })
    }

    handleSelect=(value)=>{
        this.props.form.setFields({
            approvalmemo:{errors:null},
            drawbackcode:{errors:null},
            hscode:{errors:null},
            priceisok:{errors:null},
            iseffecthscode:{errors:null},
        });
        if(value==4){
            this.state.require_other=true;
            this.state.require_memo=false;
        }else{
            this.state.require_other=false;
            this.state.require_memo=true;
        }

    };

    handleSelectBranch=(value)=>{
        this.props.form.setFields({
            branchtype:{errors:null},
        });

        if(value==1){
            this.state.require_memo=false;
            this.state.require_other=true;
        }else{
            this.state.require_memo=true;
            this.state.require_other=false;
        }

        if (value == 1) {
            //品牌类型为无品牌时，品牌名称不可填
			this.props.form.setFieldsValue({ branch: ""});
			this.setState({ branch: false });
		}
    };

    //设置海关编码
    setHscode = () =>{
        this.props.form.setFieldsValue({
            drawbackcode: null });
        let hscode = this.props.form.getFieldValue("hscode");


        if(R.isNil(hscode) || R.isEmpty(hscode)){
            this.props.dispatch({
                type: "productApproval/setHscode",
                payload: {
                    hscode : []
                }
            });
            return;
        }

        this.props.form.setFieldsValue({drawbackcode:  ""});

        this.props.dispatch({
            type: "productApproval/getHscodeByCode",
            payload: {
                hscode : hscode
            }
        });
    };

    isView=()=>{
        return this.state.type != OperatorConstant.view;
    };

    columns = [
        {title: '海关编码', dataIndex: 'hscode', key: 'hscode'},
        {title: '税局编码', dataIndex: 'taxcode', key: 'taxcode'},
        {title: '名称', dataIndex: 'name', key: 'name'},
        {title: '增值税率', dataIndex: 'zzrate', key: 'zzrate'},
        {title: '消费税率', dataIndex: 'xfrate', key: 'xfrate'},
        {title: '退税率', dataIndex: 'taxrate', key: 'taxrate'},
        {title: '监管条件', dataIndex: 'supercondition', key: 'supercondition'},
        {title: '备注', dataIndex: 'memo', key: 'memo'},
        {title: '申报要素', dataIndex: 'declarelements', key: 'declarelements'},

    ];


    render() {

        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {labelCol: { xs: {span: 8}, sm: {span: 8}}, wrapperCol: {xs: {span: 15}, sm: {span: 14}}};
        const formItemLayout2 = {labelCol: { xs: {span: 8}, sm: {span: 16}}, wrapperCol: {xs: {span: 15}, sm: {span: 20}}};
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;




        let attachmentMap = R.isNil(dataSource.attachmentMap ) ? {} : dataSource.attachmentMap
        let hscodeList=R.isNil(this.props.hscode) || R.isEmpty(this.props.hscode)? [] : this.props.hscode
        let productFacade = R.isNil(attachmentMap.productfacade)?'':attachmentMap.productfacade.url;
        let productBranchModel =R.isNil(attachmentMap.productbranchmodel) ? '':attachmentMap.productbranchmodel.url;
        let productCartons = R.isNil(attachmentMap.productcartons)?'':attachmentMap.productcartons.url;
        let productOther = R.isNil(attachmentMap.productotherfile)?'':attachmentMap.productotherfile.url;

        let options=[];
        if(!R.isEmpty(hscodeList)){
            for(let i in hscodeList){
                options.push(<Option value={hscodeList[i].taxcode}>{hscodeList[i].taxcode}</Option>)
            }
        }


        let footer = [];
        let disableProduct = this.props.disabled || this.state.type == OperatorConstant.view || this.state.type == OperatorConstant.approval;
        let disableApproval = this.state.disabled || this.state.type == OperatorConstant.view;




        if (this.state.type == OperatorConstant.approval) {
            if (this.state.disabled == false) {
                footer.push(<Button key="submit" size="large" loading={this.state.loading} disabled={disableApproval} onClick={this.handleConfirm.bind(this, OperatorConstant.approval)}
                >审核</Button>);
            }

        } else if (this.state.type != OperatorConstant.view) {
            footer.push(<Button key="submit" size="large" loading={this.state.loading} disabled={this.props.disabled} onClick={this.handleConfirm.bind(this, OperatorConstant.add)}
            >保存</Button>);

            this.props.businessType === "2" ? "" : footer.push(<Button key="primary" size="large" loading={this.state.loading} disabled={this.props.disabled} onClick={this.handleConfirm.bind(this, OperatorConstant.saveAndApproval)}
                >保存并提交审核</Button>);


        }

        footer.push(<Button key="cancel" size="large" onClick={this.handleCancel.bind(this, true)}>取消</Button>);

        let module = "product";


        return (
            <Modal maskClosable={false} footer={footer} visible={this.state.open} width={900} wrapClassName="vertical-center-modal" onCancel={this.handleCancel}
               title={"产品:" + (!R.isNil(dataSource.approvalMemo) && this.isView() ? dataSource.approvalMemo : '')} >
                <Form>
                    <div>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="品名" hasFeedback>
                                    {getFieldDecorator('name', {
                                        rules: [{
                                            required: true, message: '请输入品名'
                                        }],
                                        initialValue: dataSource.name
                                    })(
                                        <Input maxLength="30" disabled={disableProduct}/>
                                    )}
                                </FormItem></Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="英文品名" hasFeedback>
                                    {getFieldDecorator('nameEn', {
                                        rules: [{
                                            required: true, message: '请输入英文品名'
                                        }],
                                        initialValue: dataSource.nameEn
                                    })(
                                        <Input maxLength="30" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="品牌类型" hasFeedback>
                                    {getFieldDecorator('branchtype', {
                                        rules: [{
                                            required: true, message: '请选择品牌类型'
                                        }],
                                        initialValue: dataSource.branchtype
                                    })(
                                        <BizParams sprCode={"branch"} style={{ width: '100%' }} disabled={disableProduct} onChange={this.handleSelectBranch.bind(this)}/>
                                        )}
                                </FormItem></Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="品牌" hasFeedback>
                                    {getFieldDecorator('branch', {
                                        rules: [{
                                            required: this.props.form.getFieldValue("branchtype") !== '1', message: '请输入品牌'
                                        }],
                                        initialValue: dataSource.branch
                                    })(
                                        <Input maxLength="30" disabled={this.state.require_other} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="型号" hasFeedback>
                                    {getFieldDecorator('model', {
                                        rules: [{
                                            required: true, message: '请输入型号'
                                        }],
                                        initialValue: dataSource.model
                                    })(
                                        <Input maxLength="50" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="净重(kg)" hasFeedback>
                                    {getFieldDecorator('weight', {
                                        rules: [{
                                            required: true, message: '请输入净重(kg)'
                                        }],
                                        initialValue: dataSource.weight
                                    })(
                                        <InputNumber style={{ width: '100%' }} disabled={disableProduct} maxLength="18"/>
                                    )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="采购成本(CNY)" hasFeedback>
                                    {getFieldDecorator('costPrice', {
                                        rules: [{
                                            required: true, message: '请输入采购成本'
                                        }],
                                        initialValue: R.isNil(dataSource.costPrice) ? '' : dataSource.costPrice + ''
                                    })(
                                        <InputNumber style={{ width: '100%' }} disabled={disableProduct} maxLength="18"/>
                                    )}
                                </FormItem>
                            </Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="单位" hasFeedback>
                                    {getFieldDecorator('unit', {
                                        rules: [{
                                            required: true, message: '请输入单位'
                                        }],
                                        initialValue: dataSource.unit
                                    })(
                                        <Input maxLength="20" disabled={disableProduct} />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>

                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="销售价" hasFeedback>
                                    {getFieldDecorator('price', {
                                        rules: [{
                                            required: true, message: '请输入销售价'
                                        }],
                                        initialValue: R.isNil(dataSource.price) ? '' : dataSource.price + ''
                                    })(
                                        <InputNumber style={{ width: '100%' }} disabled={disableProduct} maxLength="18"/>
                                        )}
                                </FormItem></Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="销售价币种" hasFeedback>
                                    {getFieldDecorator('currency', {
                                        rules: [{
                                            required: true, message: '请输入销售价币种'
                                        }],
                                        initialValue: dataSource.currency
                                    })(
                                        <CurrencySelect disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                        </Row>

                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="历史HSCode" hasFeedback>
                                    {getFieldDecorator('hscodehis', {
                                        rules: [{
                                            required: false, message: '请输入历史HSCode'
                                        }],
                                        initialValue: dataSource.hscodehis
                                    })(
                                        <Input maxLength="20" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="规格" hasFeedback>
                                    {getFieldDecorator('size', {
                                        rules: [{
                                            required: false, message: '请输入规格'
                                        }],
                                        initialValue: dataSource.size
                                    })(
                                        <Input maxLength="50" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12}>
                                <FormItem {...formItemLayout} label="备注" hasFeedback>
                                    {getFieldDecorator('memo', {
                                        rules: [{
                                            required: false, message: '请输入备注'
                                        }],
                                        initialValue: dataSource.memo
                                    })(
                                        <Input maxLength="100" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={30}>
                                <FormItem {...{labelCol: {sm: {span: 4}}, wrapperCol: {sm: {span: 19}}}} label="申报要素" hasFeedback>
                                    {getFieldDecorator('declarelements', {
                                        rules: [{
                                            required: true, message: '请输入申报要素'
                                        }],
                                        initialValue: dataSource.declarelements
                                    })(
                                        <Input style={{ width: "100%"}} maxLength="255" disabled={disableProduct} />
                                        )}
                                </FormItem></Col>
                        </Row>
                        <Row>
                            <Col span={12} style={{ marginTop: -25 }}>
                                <FormItem {...formItemLayout} hasFeedback>
                                    <a style={{ marginLeft: 155 }} target="_blank" onClick={this.handleDownloadTable.bind(this)}>下载申报要素核对表</a>
                                    <a style={{ marginLeft: 35 }} target="_blank" href="http://www.hscode.net/IntegrateQueries/QueryYS">申报要素查询</a>
                                </FormItem>
                            </Col>
                        </Row>
                    </div>

                    <Tabs tabPosition={'top'}>
                        <TabPane tab="附件" key="1">
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout2} label="产品(含配件)整体外观图(至少1张)" hasFeedback>
                                        <SingleDragger disabled={disableProduct} url={productFacade} ref="productFacade" dataSource={dataSource} module={module}/>
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout2} label="品牌/型号确认图(有品牌或型号时必传,至少1张)" hasFeedback>
                                        <SingleDragger disabled={disableProduct} url={productBranchModel} ref="productBranchModel" dataSource={dataSource} module={module}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <FormItem {...formItemLayout2} label="产品内包装图(至少2张,分别体现不同面)" hasFeedback>
                                        <SingleDragger disabled={disableProduct} url={productCartons} ref="productCartons" dataSource={dataSource} module={module}/>
                                    </FormItem>
                                </Col>
                                <Col span={12}>
                                    <FormItem {...formItemLayout2} label="其他(可选，如历史报关单、产品说明书、质保证书)" hasFeedback>
                                        <SingleDragger disabled={disableProduct} url={productOther} ref="productOther" dataSource={dataSource} module={module}/>
                                    </FormItem>
                                </Col>
                            </Row>
                        </TabPane>
                    </Tabs>

                    {this.state.type == OperatorConstant.approval || this.state.type == OperatorConstant.view ?
                        <Tabs tabPosition={'top'}>
                            <TabPane tab="审核" key="1">

                                <Table dataSource={hscodeList} columns={this.columns} bordered={true} size={'middle'} scroll={{ x: true }} />
                                <br/>

                                <Row>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="请选择审核结果"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('approvalresult', {
                                                rules: [{
                                                    required: true, message: '请选择审核结果！',
                                                }],
                                                initialValue: R.isNil(dataSource.status) || !R.contains(dataSource.status, ["3", "4", "5"]) ? "" : dataSource.status
                                            })(
                                                <Select disabled={disableApproval} onChange={this.handleSelect.bind(this)}>
                                                    <Option value="3">退回补充资料</Option>
                                                    <Option value="4">审核通过</Option>
                                                    <Option value="5">审核不通过</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="规格是否影响海关编码"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('iseffecthscode', {
                                                rules: [{
                                                    required: this.state.require_other, message: '请选择规格是否影响海关编码！',
                                                }],
                                                initialValue: dataSource.iseffecthscode
                                            })(
                                                <Select disabled={disableApproval}>
                                                    <Option value="1">是</Option>
                                                    <Option value="0">否</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="产品价格是否合理"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('priceisok', {
                                                rules: [{
                                                    required: this.state.require_other, message: '请选择产品价格是否合理！',
                                                }],
                                                initialValue: dataSource.priceisok
                                            })(
                                                <Select disabled={disableApproval}>
                                                    <Option value="1">合理</Option>
                                                    <Option value="0">不合理</Option>
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="HSCode"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('hscode', {
                                                rules: [{
                                                    required: this.state.require_other, message: '请输入HSCode！',
                                                }],
                                                initialValue: dataSource.hscode
                                            })(
                                                <Input maxLength="20" disabled={disableApproval}
                                                       onBlur={this.setHscode.bind(this)}/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="税局HSCode"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('drawbackcode', {
                                                rules: [{
                                                    required: this.state.require_other, message: '请输入税局HSCode！',
                                                }],
                                                initialValue: dataSource.drawbackcode
                                            })(
                                                <Select disabled={disableApproval}>
                                                    {options}
                                                </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="备注"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('approvalmemo', {
                                                rules: [{
                                                    required: this.state.require_memo, message: '请输入备注！',
                                                }],
                                                initialValue: dataSource.approvalMemo
                                            })(
                                                <Input maxLength="100" disabled={disableApproval}/>
                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </TabPane>
                        </Tabs>
                        : ""}

                </Form>
            </Modal>
        );
    }
})


// WEBPACK FOOTER //
// ./public/src/components/order/components/EditProduct.js